<template>
  <div class="topic-edit-container">
    <div class="topic-manage">
      <el-button @click="handleClick" type="primary">新建题目</el-button>
      <el-button @click="importTopic" style="margin-left: 20px" type="primary"
        >导入题目
      </el-button>
      <el-button @click="setCriterion2">设置评分标准</el-button>&nbsp;&nbsp;&nbsp;
      <slot></slot>
    </div>
    <exam-paper
      :topics="topics"
      :type="2"
      :answer="answer"
      :finish="() => {}"
      :criterion="criterionCopy"
      :reviewResult="[]"
    ></exam-paper>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="onBeforeClose"
    >
      <!-- <span>这是一段信息</span> -->
      <import-topic
        v-if="contentCode == 0"
        :searchResults="searchResults"
        :setSearchResults="setSearchResults"
      ></import-topic>

      <!--   为设置评分标准   -->
      <el-form v-else :model="criterionCopy" label-width="80px">
        <el-form-item
          v-for="item in formTemplate"
          :key="item.label"
          :label="item.label"
        >
          <el-input v-model.number="criterionCopy[item.bindKey]"></el-input>
        </el-form-item>
        <el-form-item
          v-show="topicIds.essayQuestion.length !== 0"
          label="问答题"
        >
          <el-input
            placeholder="示例：10 10 12"
            v-model="criterionCopy['essayQuestion']"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
import ExamPaper from "./ExamPaper.vue";
import ImportTopic from "@/components/ImportTopic.vue";

/**
 * 设置评分标准的逻辑，
 * 看看topicIds里有哪些题型，这里要看length。对于有的题型去按照不同的设置方法
 * 除了应用题，其他的都是一个数字
 */
export default {
  name: "TopicEditBlock",
  components: {
    ExamPaper,
    ImportTopic,
  },
  props: ["topicIds", "setCriterion", "operTopicIds"],
  data() {
    return {
      topics: {
        singleChoice: [],
        multipleChoice: [], //多选
        trueOrFalse: [], //判断
        blankQuestion: [], //填空
        essayQuestion: [], //问答
      },
      dialogVisible: false,

      contentCode: -1, //内容代码，初始为-1，打开搜索题目为0，打开设置评分标准为1
      criterionCopy: {},
      formTemplate: [
        {
          label: "单选题",
          bindKey: "singleChoice",
        },
        {
          label: "多选题",
          bindKey: "multipleChoice",
        },
        {
          label: "判断题",
          bindKey: "trueOrFalse",
        },
        {
          label: "填空题",
          bindKey: "blankQuestion",
        },
      ],
      searchResults: [],
    };
  },
  methods: {
    onBeforeClose(done) {
      this.searchResults = [];
      done();
    },
    // ...mapMutations(),
    setSearchResults(searchResults) {
      this.searchResults = searchResults;
    },
    ...mapMutations("windowAbout", ["OPEN"]),
    handleClick() {
      this.OPEN();
    },
    getTopicKey(topicType) {
      const typeMapKey = {
        sc: "singleChoice",
        mc: "multipleChoice",
        tof: "trueOrFalse",
        bl: "blankQuestion",
        an: "essayQuestion",
      };
      return typeMapKey[topicType];
    },
    //设置评判标准的回调
    setCriterion2() {
      this.formTemplate = this.computeFormTemplate();
      this.contentCode = 1;
      this.dialogVisible = true;
    },
    //导入题目的回调
    importTopic() {
      this.contentCode = 0;
      this.dialogVisible = true;
    },
    //表单确认的回调
    confirm() {
      if (this.contentCode === 0) {
        //  导入搜索题目的逻辑
        /**
         * 拿到所有checked的然后加入到topics中，分成两个部分一个部分是topicIds，一个是显示用的topics
         */
        const checkedTopics = this.searchResults.filter(
          (topic) => topic.checked
        );
        for (const checkedTopic of checkedTopics) {
          this.topics[checkedTopic.type].push(checkedTopic);
          this.operTopicIds(checkedTopic.type, checkedTopic.tid);
        }
        this.searchResults = [];
      } else {
        //  设置评判标准的逻辑
        const { essayQuestion } = this.criterionCopy;
        if (essayQuestion !== undefined) {
          const scores = essayQuestion.split(" ");
          const regex = /^[\d\s]+$/;
          // console.log(scores)
          if (!regex.test(essayQuestion)) {
            alert("格式不对");
            return;
          }
          if (scores.length !== this.topicIds.essayQuestion.length) {
            console.log(scores.length);
            alert("问答题数量不对");
            return;
          }
          this.criterionCopy.essayQuestion = scores.map((v) => v * 1);
        }
        //一下逻辑临时用

        this.setCriterion(this.criterionCopy);
      }
      this.dialogVisible = false;
    },
    //  计算formTemplate的逻辑
    computeFormTemplate() {
      const res = [];
      if (this.topicIds.singleChoice.length !== 0) {
        res.push({
          label: "单选题",
          bindKey: "singleChoice",
        });
      }
      if (this.topicIds.multipleChoice.length !== 0) {
        res.push({
          label: "多选题",
          bindKey: "multipleChoice",
        });
      }
      if (this.topicIds.trueOrFalse.length !== 0) {
        res.push({
          label: "判断题",
          bindKey: "trueOrFalse",
        });
      }
      if (this.topicIds.blankQuestion.length !== 0) {
        res.push({
          label: "填空题",
          bindKey: "blankQuestion",
        });
      }
      return res;
    },
  },
  //组件挂载时订阅消息 声明当有人发送了该主题的消息时执行的回调
  mounted() {
    this.listenChannel = new BroadcastChannel("topic");
    this.listenChannel.onmessage = (msg) => {
      // console.log(msg);
      const { data: topic } = msg;
      const topicKey = this.getTopicKey(topic.topicType);
      topic.order = this.topics[topicKey]?.length + 1;
      this.topics[topicKey]?.push(topic);

      // 加入到id数组
      // this.topicIds.singleChoice.push(topic.tid);
      this.operTopicIds(topicKey, topic.tid);
    };
  },
  computed: {
    answer() {
      return [];
      // const answer = [];
      // const order = [
      //   "singleChoice",
      //   "multipleChoice",
      //   "trueOrFalse",
      //   "blank",
      //   "essay",
      // ];
      // for (let currentTopicType of order) {
      //   for (let topic of this.topics[currentTopicType]) {
      //     answer.push(topic.answer);
      //   }
      // }
      // return answer;
    },
  },
  // 被销毁前取消订阅消息
  beforeDestroy() {
    console.log("取消全局广播");
    this.listenChannel.close();
  },
};
</script>

<style lang='less' scoped>
.topic-manage {
  display: flex;
  margin-bottom: 20px;
}

.title {
  font-size: 20px;
  font-weight: bold;
}
</style>